package com.kws.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.exception.ServiceException;
import com.kws.system.config.MinioAPI;
import com.kws.system.domain.TbExtendImage;
import com.kws.system.domain.vo.UpdateExtendRq;
import com.kws.system.mapper.ExtendImageMapper;
import com.kws.system.service.ExtendImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <b>ExtendImageServiceImpl</b>
 *
 * @description: ExtendImageServiceImpl <br>
 * @date: 2024/12/3 17:29 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class ExtendImageServiceImpl extends ServiceImpl<ExtendImageMapper, TbExtendImage> implements ExtendImageService {
    private static final Logger logger = LoggerFactory.getLogger(ExtendImageServiceImpl.class);

    @Autowired
    private MinioAPI minioAPI;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    @Override
    public void createExtendImage(Long id, List<MultipartFile> files) {
        List<TbExtendImage> saveList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(files)){
            files.forEach(item -> {
                TbExtendImage tbExtendImage = new TbExtendImage();
                tbExtendImage.setExtendId(id);
                tbExtendImage.setFileName(item.getOriginalFilename());
                String url = uploadFile(item);
                tbExtendImage.setImageUrl(url);
                saveList.add(tbExtendImage);
            });
            this.saveBatch(saveList);
        }
    }

    @Override
    public void updateExtendImage(UpdateExtendRq rq) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("extend_id",rq.getId());
        queryWrapper.notIn("id",rq.getIds());
        baseMapper.delete(queryWrapper);

        if (CollectionUtil.isNotEmpty(rq.getFiles())){
            List<TbExtendImage> saveList = new ArrayList<>();
            rq.getFiles().forEach(item -> {
                TbExtendImage tbExtendImage = new TbExtendImage();
                tbExtendImage.setExtendId(rq.getId());
                tbExtendImage.setFileName(item.getOriginalFilename());
                String url = uploadFile(item);
                tbExtendImage.setImageUrl(url);
                saveList.add(tbExtendImage);
            });
            this.saveBatch(saveList);
        }
    }

    public String uploadFile(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}"+objectKey);
            return minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    private String getObjectKey(Long fileSize,String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }
}
